package com.example.factory.api.dto.assembler;

import com.example.factory.api.dto.DtoRole;
import com.example.factory.api.dto.form.DtoRoleForm;
import com.example.factory.core.domain.RoleEntity;
import com.example.factory.core.repository.RoleEntityRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lei Tao
 */
@Component
public class RoleAssembler {
    private final RoleEntityRepository roleEntityRepository;

    public RoleAssembler(RoleEntityRepository roleEntityRepository) {
        this.roleEntityRepository = roleEntityRepository;
    }

    public List<DtoRole> toDtoRole(List<RoleEntity> roleEntities) {
        return roleEntities.stream().map(this::toDtoRole).collect(Collectors.toList());
    }

    public DtoRole toDtoRole(RoleEntity roleEntity) {
        DtoRole dtoRole = new DtoRole();
        BeanUtils.copyProperties(roleEntity, dtoRole);
        return dtoRole;
    }

    public RoleEntity toRole(DtoRoleForm dtoRoleForm) {
        RoleEntity roleEntity;
        if (!StringUtils.isEmpty(dtoRoleForm.getGuid())){
            roleEntity = roleEntityRepository.findByGuidAndArchivedFalse(dtoRoleForm.getGuid());
        }else {
            roleEntity = new RoleEntity();
        }
        BeanUtils.copyProperties(dtoRoleForm,roleEntity);
        roleEntity.setAdmin(dtoRoleForm.isAdmin());
        return roleEntity;
    }
}
